﻿CREATE PROCEDURE [dbo].[ManufacturesInsert]
(
	@CountryId int,
	@Name varchar(100),
	@ShortName varchar(50),
	@LatName varchar(50),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
SET NOCOUNT ON

IF (@Name Is Null) OR (@ShortName Is Null) OR (@CountryId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (ltrim(@Name) = '') OR (ltrim(@ShortName) = '')
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Незаполнено наименование или короткое наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT TOP 1 ID FROM [CO].[Manufacturers] WHERE Name = @Name OR ShortName = @ShortName) 
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Дублируется наименование или короткое наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT ID FROM [CO].[Manufacturers] WHERE (Name = @Name OR ShortName = @ShortName) AND ToDelete = 0) 
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Изменять данные спрвочников можно только в офисе!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CO].[Manufacturers] (Id, [CountryId], [Name], [ShortName], [LatName], 
[Note], [MD], [MW], ToDelete)
VALUES (@intNextId, @CountryId, @Name, @ShortName, @LatName, @Note, @MD, @MW, 0);
	
SELECT Id, CountryId, Name, ShortName, LatName, Note, MD, MW, ToDelete
FROM CO.Manufacturers WHERE (Id = @intNextId)
RETURN 0

